package net.zoneland.knowledge.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.zoneland.knowledge.model.ErrorCorrection;
import net.zoneland.knowledge.model.QaSatisfaction;
import net.zoneland.uniflow.client.TaskObject;
import net.zoneland.uniflow.client.UserInfo;

/**
 * 邮件内容工具类.
 *
 * @author zmq
 * 2021/11/24 17:04
 */
public final class EmailContentUtils {
    /**
     * 日志.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(EmailContentUtils.class);


    /**
     * 邮件模板.
     */
    private static final String EMAIL_CONTENT_TEMPLATE = "<table border=1 cellpadding=0 cellspacing=0 width=549 >"
            + "<col width=124><col width=425>"
            + "<tr style='height:13.5pt;background-color:lightblue'>"
            + "<td colspan=2 class=xl68 width=549 style='height:13.5pt;width:412pt'>"
            + "您在 智慧人力共享赋能中心（HR SEC） 下有 ${subject} 工单需要审批</td></tr>"
            + "<tr ><td >工单号</td><td >${applyId}</td></tr>"
            + "<tr ><td >工单标题</td><td >${subject}</td></tr>"
            + "<tr><td>发送者</td><td>${handlerName}</td></tr>"
            + "<tr ><td>工单创建时间</td><td >${applyDate}</td></tr>"
//        + "<tr ><td >通知发送时间</td><td >${now}</td></tr>"
            + "<tr ><td >当前处理人</td><td >${ownerNames}</td></tr>"
            + "<tr ><td colspan=2>[<a target='_blank' style='color:blue' href='${viewUrl}'><u>待办处理</u></a>]</td>"
            + "<td style='text-align:right'></td></tr>"
            + "</table>";

    /**
     * 祝福语模版。
     */
    private static final String CONGRATULATE_WORDS_TEMPLATE =
            "<div style='margin-top:10px;margin-bottom: 15px;font-family: 微软雅黑; font-size: 16px;'>"
                    + "<span style='width:320px;'>${words}</span></div>";

    /**
     * 投递模版。
     */
    private static final String CONGRATULATE_DELIVERY_TEMPLATE =
            " <div style='margin-top: 6px;font-family: 微软雅黑; font-size: 16px;'>【智慧人力共享赋能中心（HR&nbsp;SEC）】&nbsp;</div>";


    /**
     * 祝福标题模版。
     */
    private static final String CONGRATULATE_TITLE_TEMPLATE =
            "<div style='font-family: 微软雅黑; font-size: 16px;'>${birthdayDate}是您的生日，<b>${cName}&nbsp;</b>送来了祝福</div>";

    /**
     * 祝福贺卡图片模版。
     */
    private static final String CONGRATULATE_IMG_TEMPLATE = "${words}<div> <img src='${img}'></div>${delivery}";

    /**
     * url模板.
     */
    private static final String URL_TEMPLATE = "tiid=${tiid}&piid=${piid}&systemId=aitalk"
            + "&businessProcess=${businessProcess}&nodeId=${nodeId}"
            + "&applyId=${applyId}";
    /**
     * 竖杠分隔符.
     */
    private static final String SPLIT_SHU_CHAR = "\\|";

    /**
     * 私有日志.
     */
    private EmailContentUtils() {

    }

    /**
     * 构造纠错邮件提醒内容.
     *
     * @param errorCorrection 纠错
     * @param taskObject      任务信息
     * @param url             待办处理前缀
     * @return 邮件提醒内容
     */
    public static String buildEmailContent(final ErrorCorrection errorCorrection,
                                           final TaskObject taskObject, final String url) throws UnsupportedEncodingException {
        return EmailContentUtils.EMAIL_CONTENT_TEMPLATE.replace("${subject}", taskObject.getApplyTitle())
                .replace("${applyId}", taskObject.getApplyId())
                .replace("${handlerName}", taskObject.getApplicant().getUserName())
                .replace("${applyDate}", DateHelper.getDateTime(errorCorrection.getCreateTime()))
                .replace("${ownerNames}", errorCorrection.getHandlerName())
                .replace("${viewUrl}", url + "?" + EmailContentUtils.buildDealUrl(taskObject))
//            .replace("${now}", DateHelper.getDateTime(Calendar.getInstance().getTime()))
                ;
    }

    /**
     * 构造满意度反馈邮件提醒内容.
     *
     * @param qaSatisfaction 满意度
     * @param taskObject     任务信息
     * @param url            待办处理前缀
     * @return 邮件提醒内容
     */
    public static String buildEmailContent(final QaSatisfaction qaSatisfaction,
                                           final TaskObject taskObject, final String url) throws UnsupportedEncodingException {
        return EmailContentUtils.EMAIL_CONTENT_TEMPLATE.replace("${subject}", taskObject.getApplyTitle())
                .replace("${applyId}", taskObject.getApplyId())
                .replace("${handlerName}", taskObject.getApplicant().getUserName())
                .replace("${applyDate}", DateHelper.getDateTime(new Date(taskObject.getCreateTime())))
                .replace("${ownerNames}", taskObject.getHandler().getUserName())
                .replace("${viewUrl}", url + "?" + EmailContentUtils.buildDealUrl(taskObject))
//            .replace("${now}", DateHelper.getDateTime(Calendar.getInstance().getTime()))
                ;
    }

    /**
     * 构造生日祝福邮件内容.
     *
     * @param birthdayDate 生日日期
     * @param cName        祝福人中文名称
     * @param words        祝福语
     * @param img          图片路径链接或者base64的图片
     * @return 生日祝福内容
     */
    public static String buildCongratulateEmailContent(final String birthdayDate, final String cName,
                                                       final String words, final String img) {
        final StringBuffer sb = new StringBuffer(EmailContentUtils.CONGRATULATE_TITLE_TEMPLATE
                .replace("${birthdayDate}", birthdayDate).replace("${cName}", cName));
        String wordsHtml = "";
        if (StringUtils.isNotBlank(words)) {
            wordsHtml = EmailContentUtils.CONGRATULATE_WORDS_TEMPLATE.replace("${words}", words);
        }
        if (StringUtils.isNotBlank(img)) {
            sb.append(EmailContentUtils.CONGRATULATE_IMG_TEMPLATE.replace("${img}", img).replace("${words}", wordsHtml)
                    .replace("${delivery}", EmailContentUtils.CONGRATULATE_DELIVERY_TEMPLATE));
        } else {
            sb.append(wordsHtml).append(EmailContentUtils.CONGRATULATE_DELIVERY_TEMPLATE);
        }
        return sb.toString();
    }

    public static void main(final String[] args) {
        final String img = "https://igotone.zj.chinamobile.com/zjmoa-file/birthdayCard/120_hb2.jpg";
        final String words = "以梦为马，不负韶华。生日快乐！";
        final String birthdayDate = "2月24日";
        final String cName = "赵欣晨";
        final String contentHtml = EmailContentUtils.buildCongratulateEmailContent(birthdayDate, cName, words, img);
        System.out.println(contentHtml);
    }

    /**
     * 构造待办处理url.
     *
     * @param taskObject 任务信息
     * @return url后缀
     */
    public static String buildDealUrl(final TaskObject taskObject) {
        final UserInfo applicant = taskObject.getApplicant();
        return EmailContentUtils.URL_TEMPLATE.replace("${tiid}", EmailContentUtils.encodeURI(taskObject.getTiid()))
                .replace("${piid}", EmailContentUtils.encodeURI(taskObject.getPiid()))
                .replace("${businessProcess}", taskObject.getBusinessProcess())
                .replace("${applyId}", taskObject.getApplyId())
                .replace("${nodeId}", taskObject.getNodeId());
    }

    /**
     * 编码.
     *
     * @param val 字符串
     * @return 编码结果
     */
    private static String encodeURI(final String val) {
        try {
            return URLEncoder.encode(val, "utf-8");
        } catch (final UnsupportedEncodingException e) {
            EmailContentUtils.LOGGER.error("编码失败：{}", val, e);
        }
        return "";
    }
}
